package com.stone.framework.workflow.service;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.service.ProcessService;
import com.bstek.uflo.service.StartProcessInfo;
import com.stone.framework.workflow.client.BasicClient;
import com.stone.framework.workflow.definition.BusinessKey;
import com.stone.framework.workflow.definition.BusinessType;

@Service
public class UfloProcessService {

    @Autowired
    @Qualifier("uflo.processService")
    private ProcessService processService;

    @Autowired
    private BasicClient basicClient;

    @Transactional(transactionManager = "ufloPlatformTransactionManager")
    public ProcessInstance startProcessByName(BusinessType businessType, Map<String, Object> params) {
        return this.startProcessByName(businessType, params, true);
    }

    @Transactional(transactionManager = "ufloPlatformTransactionManager")
    public ProcessInstance startProcessByName(BusinessType businessType, Map<String, Object> params,
        boolean completeStartTask) {
        String promoter = (String)params.get(BusinessKey.PROMOTER);
        String businessId = (String)params.get(BusinessKey.BUSINESS_ID);

        Assert.notNull(businessType, "[businessType] must not be null");
        Assert.notNull(promoter, "[promoter] must not be null");
        Assert.notNull(businessId, "[businessId] must not be null");

        String subject = (String)params.get(BusinessKey.SUBJECT);
        String tag = (String)params.get(BusinessKey.TAG);
        String completeStartTaskOpinion = (String)params.get(BusinessKey.OPINION);

        Map<String, Object> variables = params;

        // TODO 数据字典
        String businessTypeName = basicClient.getKV("").getOrDefault(businessType.name(), "");
        variables.put(BusinessKey.BUSINESS_TYPE, businessType.name());
        variables.put(BusinessKey.BUSINESS_TYPE_NAME, businessTypeName);

        StartProcessInfo startProcessInfo = new StartProcessInfo();
        startProcessInfo.setPromoter(promoter);
        startProcessInfo.setBusinessId(businessId);
        startProcessInfo.setSubject(subject);
        startProcessInfo.setTag(tag);
        startProcessInfo.setCompleteStartTask(completeStartTask);
        startProcessInfo.setCompleteStartTaskOpinion(completeStartTaskOpinion);
        startProcessInfo.setVariables(variables);

        return processService.startProcessByName(businessType.name(), startProcessInfo);
    }

}
